package com.ishahid.translationbot;

import com.google.wave.api.*;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

@SuppressWarnings("serial")
public class TranslationBotServlet extends AbstractRobotServlet {
	public static PersistenceManager pm = null;
	private WaveObject waveObj;
	private Language langTo;
	
	@SuppressWarnings("unchecked")
	@Override
	public void processEvents(RobotMessageBundle bundle) {
		Wavelet wavelet = bundle.getWavelet();
		
		if (pm == null) {
	        pm = PMF.get().getPersistenceManager();
	    }
		
		/* Add configuration gadget here */
		if (bundle.wasSelfAdded()) {
			Gadget gadget = new Gadget("http://translate-wave.appspot.com/gadget/config.xml");
	        gadget.setField("wid", wavelet.getWaveId());
	        TextView text = wavelet.appendBlip().getDocument();
	        text.getGadgetView().append(gadget);
		}
		
		/* Process the events here */
		for (Event e: bundle.getEvents()) {
			if (e.getType() == EventType.BLIP_SUBMITTED) {    
				Blip blip = e.getBlip();
		        
				Query query = pm.newQuery(WaveObject.class);
	            query.setFilter("waveId == waveidParam");
	            query.declareParameters("String waveidParam");

	            try {
	                List<WaveObject> results = (List<WaveObject>) query.execute(wavelet.getWaveId().replace("+", " "));
	                waveObj = results.get(0);
	            } finally { query.closeAll(); }

	            if (waveObj != null) {
	                Translate.setHttpReferrer("http://translate-wave.appspot.com/");
					String translatedText = null;
					String styledText = null;
			
					try {
						langTo = Language.fromString(waveObj.getLanguage());
						translatedText = Translate.execute(blip.getDocument().getText(), Language.AUTO_DETECT, langTo);
						styledText = blip.getDocument().getText() + "<br/><br/><i>Translated in " + langTo.name() + " as:<br/>" + translatedText + "</i>";
						blip.getDocument().replace("");
						blip.getDocument().appendMarkup(styledText);
					} catch (Exception ex) {
						Logger.getLogger(TranslationBotServlet.class.getName()).log(Level.SEVERE, null, ex);
						styledText = blip.getDocument().getText() + "<br/><br/><i>Error in translation:<br/>" + ex.toString() + "</i>";
						blip.getDocument().replace("");
						blip.getDocument().appendMarkup(styledText);
					}
	            }
		    }
	    }
	}
}
